/*
**  crc.c - simple checksumming (add)
**  Copyright (C) 1996 Joachim Ott <ott@ardala.han.de>
**
**  This program is free software; you can redistribute it and/or modify
**  it under the terms of the GNU General Public License as published by
**  the Free Software Foundation; either version 2 of the License, or
**  (at your option) any later version.
**
**  This program is distributed in the hope that it will be useful,
**  but WITHOUT ANY WARRANTY; without even the implied warranty of
**  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
**  GNU General Public License for more details.
**
**  You should have received a copy of the GNU General Public License
**  along with this program; if not, write to the Free Software
**  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
**
** $Id: crc.c,v 1.2 1999/04/17 16:28:10 ott Exp $
*/

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <sys/types.h>

#include "libbtm.h"
#include "crc.h"

/* ------------------------------------- local data ----------------------- */

static ulong	c_csum;
static ulong	r_csum;
static ulong	w_csum;

/* ------------------------------------------------------------------------ */

void
c_clear (void)
{
	c_csum = 0;
	r_csum = 0;
	w_csum = 0;
}

/* ------------------------------------------------------------------------ */

int
c_valid (void)
{
	if (c_csum != r_csum)
	{
		char m [128];

		sprintf (m, "crc calc %lu read %lu\n", c_csum, r_csum);
		m_log ("crc-check", m);
		return (1);
	}

	return (0);
}

/* ------------------------------------------------------------------------ */

char *
c_read (FILE *fd)
{
	static char in_buf [LINESIZ];
	int i;
	ulong csum;
	char *p;

	memset (in_buf, 0, LINESIZ);

	if (fgets (in_buf, LINESIZ, fd) == NULL)
		return (NULL);

	/* The checksum-line is the last line of the file.  */

	if (sscanf (in_buf, "chksum=%lu", &csum) == 1)
	{
		r_csum = csum;
		return (NULL);
	}

	for (i = 0; in_buf [i] != 0x00; ++i)		/* update crc for this line */
		c_csum += (ulong) ((unsigned char) in_buf [i]);

	if ((p = strchr (in_buf, '\n')) != NULL)	/* discard LF if present */
		*p = 0x00;

	return (in_buf);
}

/* ------------------------------------------------------------------------ */

int
c_write (FILE *fd, char *buf)
{
	static char out_buf [LINESIZ];
	int i, j;

	if (buf == NULL)
	{
		fprintf (fd, "chksum=%lu\n", w_csum);
		return (0);
	}

	if ((strlen (buf) + 1) > LINESIZ)
	{
		char m [128];

		strncpy (m, buf, 32);
		strcat (m, "... - Zeile zu lang\n");
		m_log ("c_write", m);
		return (-1);
	}

	memset (out_buf, 0, LINESIZ);

	j = sprintf (out_buf, "%s\n", buf);

	for (i = 0; out_buf [i] != 0x00; ++i)
		w_csum += (ulong) ((unsigned char) out_buf [i]);

	i = fprintf (fd, out_buf);

	return (i - j);	/* zero when okay */
}

/* ------------------------------------------------------------------------ */

/* crc.c */
